/*================ server_coord.c ======================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "server_coord.h"
#include "coord.h"


/* Create a new server_coord struct */
server_coord create_server_coord(const char* server_name, char* servers[], int coord_size){
	int i = 0;
	server_coord server = (server_coord) calloc(1, sizeof(struct _server_coord));

	server->name = (char*) calloc(strlen(server_name), sizeof(char));

	strcpy(server->name, server_name);

	for(i = 0; i < 100 && i < coord_size; ++i){
		char* aux = (char*) calloc(strlen(servers[i]), sizeof(char));
		strcpy(aux, servers[i]);

		char* server_name_aux = strtok(aux, " ");

		char *north_s = strtok(NULL, ":");
		char *este_s = strtok(NULL, " :\n\t");
		strtok(NULL, " :\n\t");

		int north = atoi(north_s);
		int este = atoi(este_s);
		server->coords[i] = create_coord(server_name_aux, north, este);
		free(aux);
	}

	return server;
}

/* delete a server_coord struct */
void delete_server_coord(server_coord *server){
	int i;
	free((*server)->name);
	for(i = 0; i < 100 && (*server)->coords[i] != NULL; ++i){
		delete_coord(&((*server)->coords[i]));
	}
	free(*server);
	*server= NULL;
}

/* print to stdout a server_coord struct */
void print_server_coord(const server_coord server){
	int i;

	if(server != NULL){
		if (server->name != NULL || server->coords != NULL){
			printf("server-%s -- ", server->name);
			for(i = 0; i < 100 && server->coords[i] != NULL; ++i){
				print_coord(server->coords[i]);
				printf(" - ");
			}
				printf("\n");
		}
			else
				printf("Erro: NULL server_coord member\n");
	}
	else
		printf("Erro: NULL server_coord\n");
}
